package com.alibaba.www.controller;


import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.TypeReference;
import com.junmoo.www.entity.SysRole;
import com.junmoo.www.entity.SysUser;
import com.junmoo.www.tool.JwtUtils;
import com.junmoo.www.tool.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import reactor.core.publisher.Mono;
import java.util.List;
import java.util.Set;


@RefreshScope//实现配置自动更新
@RestController
@RequestMapping
public class ProviderController {
    @Autowired
    RedisTemplate redisTemplate;
//    @PreAuthorize("hasRole('user')")
    @GetMapping(value = "/info")
    public Mono<Result> getInfo(ServerHttpRequest request) {
        String requestTokenHeader = request.getHeaders().getFirst("inner");
        System.out.println("--- 请求头 ----"+ requestTokenHeader);
        if (requestTokenHeader == null || !requestTokenHeader.startsWith("Bearer ")) {
            return Mono.just(Result.error());
        }
        String requestToken = requestTokenHeader.substring(7);
        SysUser user = JSONObject.parseObject(JwtUtils.getSubject(requestToken), SysUser.class);
        if(user==null) {
            return  Mono.just(Result.error());
        }
        String redis_refresh_token = (String)redisTemplate.opsForHash().get(user.getUsername(),"token");
        String userStr = (String)redisTemplate.opsForHash().get(user.getUsername(),"user");
        String roleStr = (String)redisTemplate.opsForHash().get(user.getUsername(),"role");
        String authStr = (String)redisTemplate.opsForHash().get(user.getUsername(),"auth");
        SysUser redisUser = JSONObject.parseObject(userStr,SysUser.class);
        List<SysRole> redisRoles = JSONObject.parseObject(roleStr, new TypeReference<List<SysRole>>(){});
        Set<SimpleGrantedAuthority> redisAuths = JSONObject.parseObject(authStr,new TypeReference<Set<SimpleGrantedAuthority>>(){});
        System.out.println("-------redisUser------\n"+redisUser+"\n----------");
        System.out.println("-------redisRoles-----\n"+redisRoles+"\n---------");
        System.out.println("-------redisAuths-----\n"+redisAuths+"\n----------");
        return  Mono.just(Result.success("success","hello world !!!!"));
    }
}
